import { useLocation, useRoutes, useNavigate } from "react-router-dom";
import { constantRoutes, asyncRoutes } from "@/pages/index.jsx"
import { useEffect, useMemo } from "react";
import { useSelector, useDispatch } from "react-redux";
import { getInfo } from "@/store/action"
import { generateRoutes } from '@/store/permission.js'
// Permission这个文件就是页面真正能展示的文件
// 可以将他用作路由守卫

const whiteList = ['/login']
export default () => {
    const { token, roles, accessRoutes } = useSelector(state => state.use)
    // 先登录,token发生变化,就又执行了这个fn1
    // 果然,在清除本地的token后,就只有getinfo这个起作用
    const dispatch = useDispatch()
    const navigator = useNavigate()
    const { pathname } = useLocation()
    // 使用副作用来监听用户变化,获取用户信息
    // 当token发生变化时就是用户发生了变化
    useEffect(() => {
        if (token) {
            dispatch(getInfo())
        } else {
            navigator("/login", { replace: true })
        }
    }, [token])

    useEffect(() => {
        if (roles && roles.length > 0) {
            // 接口返过来的用户信息，里面如果有角色信息，那么就根据角色信息来分配可访问的路由
            dispatch(generateRoutes(asyncRoutes, roles))
        }
    }, [roles])
    useEffect(() => {
        if (accessRoutes && accessRoutes.length > 0) {
            navigator("/dashboard", { replace: true })
        }
    }, [accessRoutes])
    useEffect(() => {
        if (!whiteList.includes(pathname) && !token) {
            navigator("/login", { replace: true })
        }
        if (token && pathname === "/login") {
            navigator("/", { replace: true })
        }
        if (token && pathname === "/") {
            navigator("/dashboard", { replace: true })
        }
    }, [pathname])
    // 计算全部的路由规则
    const routes = useMemo(() => {
        const result = [...constantRoutes];
        result[0].children = accessRoutes
        return result
    }, [accessRoutes])
    // console.log("所有的路由规则:", routes);
    const element = useRoutes(constantRoutes)
    return element
}